const todayPlanTable = require('../models/todayPlanTable');
const inspirecloud = require('@byteinspire/inspirecloud-api');
const ObjectId = inspirecloud.db.ObjectId;


class todayPlanService {
    /**
     * 列出所有今日计划
     * @return {Promise<Array<any>>} 返回今日计划数组
     */
    async listAll() {
        return await todayPlanTable.where({is_delete: false}).sort({createAt: -1}).find();
    }

    /**
     * 列出分页内今日计划
     */
    async queryPage(params) {
        let {page, limit, user_id, state} = params;
        let queryParams = {is_delete: false}
        if (user_id !== undefined && user_id.trim() !== '') {
            queryParams.user_id = user_id;
        }
        if (state !== undefined && state.trim() !== '') {
            queryParams.state = state;
        }
        //console.log(queryParams)
        return await todayPlanTable.where(queryParams)
            .skip((page - 1) * limit)
            .limit(limit)
            .sort({priority: 1}).find();
    }


    async getOneById(id) {
        return await todayPlanTable.where({_id: ObjectId(id)}).findOne();
    }


    /**
     * 创建一条今日计划
     * @param todayPlan 用于创建今日计划的数据，原样存进数据库
     * @return {Promise<any>} 返回实际插入数据库的数据，会增加_id，createdAt和updatedAt字段
     */
    async create(todayPlan) {
        return await todayPlanTable.save(todayPlan);
    }

    /**
     * 删除一条今日计划
     * @param id 今日计划的 _id
     * 若不存在，则抛出 404 错误
     */
    async delete(id) {
        const todayPlan = await todayPlanTable.where({_id: ObjectId(id)}).findOne();
        if (!todayPlan) {
            const error = new Error(`todayPlan:${id} not found`);
            error.status = 404;
            throw error;
        }
        todayPlan.is_delete = true;
        await todayPlanTable.save(todayPlan);
    }


    /**
     * 更新一条今日计划
     * @param newtodayPlan._id 将会用原对象 merge 此对象进行更新
     * 若不存在，则抛出 404 错误
     */
    async update(newtodayPlan) {
        const todayPlan = await todayPlanTable.where({_id: ObjectId(newtodayPlan._id)}).findOne();
        if (!todayPlan) {
            const error = new Error(`todayPlan:${newtodayPlan._id} not found`);
            error.status = 404;
            throw error;
        }
        Object.assign(todayPlan, newtodayPlan);
        todayPlan._id = ObjectId(todayPlan._id)
        await todayPlanTable.save(todayPlan);
    }
}

// 导出 Service 的实例
module.exports = new todayPlanService();
